package com.lancoo.klgcourseware.manager;

import android.content.Context;
import android.content.DialogInterface;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;

import androidx.fragment.app.FragmentManager;

import com.android.tu.loadingdialog.LoadingDailog;
import com.lancoo.klgcourseware.R;
import com.lancoo.klgcourseware.api.KlgEnglishApi;
import com.lancoo.klgcourseware.api.PassTrainApi;
import com.lancoo.klgcourseware.entity.ChineseMeaning;
import com.lancoo.klgcourseware.entity.DigitalizeCodeResponce;
import com.lancoo.klgcourseware.entity.ESPCardSource;
import com.lancoo.klgcourseware.entity.EnglishCardSource;
import com.lancoo.klgcourseware.entity.ExpressionAndUsageModel;
import com.lancoo.klgcourseware.entity.KlgApiResponse;
import com.lancoo.klgcourseware.entity.ObsConfigMsgBean;
import com.lancoo.klgcourseware.entity.ResourcePlatFormConfigure;
import com.lancoo.klgcourseware.entity.WordExplainModel;
import com.lancoo.klgcourseware.entity.bean.DigitalizeCodeBean;
import com.lancoo.klgcourseware.entity.bean.KlgCardDialogConfigBean;
import com.lancoo.klgcourseware.entity.bean.KlgCommonBean;
import com.lancoo.klgcourseware.entity.bean.KlgDbConstant;
import com.lancoo.klgcourseware.entity.passTrain.PassTrainResponce;
import com.lancoo.klgcourseware.entity.passTrain.WordBookRequestBean;
import com.lancoo.klgcourseware.utils.UniCodeUtils;

import org.jetbrains.annotations.NotNull;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import lancoo.com.net.retrofitrxjava.NetworkTransformer;
import lancoo.com.net.retrofitrxjava.network.Network;
import lancoo.com.net.retrofitrxjava.subscriber.NormalSubscriber;

/**
 * Created by pengmi on 2019/8/19 9:35
 * Description:知识点卡片弹窗管理器
 */
public class KlgCardDialogManager {

    private static final String TAG = "KlgCardDialogManager";

    private static long time;
    private static WeakReference<LoadingDailog> mLoadingDailog;
    private static List<KlgCommonBean> klgCommonBeanList;
    private static int currentKlgIndex;
    private static WeakReference<Disposable> disposable;


    /**
     * 通过ID查询
     */
    public static void openKlgCardByID(Context mContext,FragmentManager fragmentManager,String klgCode,String klgUrl,
                                       KlgCardDialogConfigBean bean,KlgCardDismissListener listener){
        openKlgCardByID(mContext,fragmentManager,klgCode,klgUrl,bean,listener,null);
    }

    /**
     * 通过ID查询
     */
    public static void openKlgCardByID(Context mContext,FragmentManager fragmentManager,String klgCode,String klgUrl,
                                       KlgCardDialogConfigBean bean,KlgCardDismissListener listener,LoadingDailog loadingDailogs){
        if(KlgCourseWareManager.getVipLimitState(mContext)){
            KlgCourseWareManager.showTrainAgainDialog();
            return;
        }

        if(System.currentTimeMillis()-time<300){
            return;
        }
        time=System.currentTimeMillis();
        getDigitalizeCode(mContext,fragmentManager,klgCode,bean,listener);
        if(loadingDailogs!=null){
            mLoadingDailog=new WeakReference<>(loadingDailogs);
            return;
        }
        if(mLoadingDailog!=null&&mLoadingDailog.get()!=null&&
            mLoadingDailog.get().isShowing()){
            return;
        }
        LoadingDailog.Builder builder = new LoadingDailog.Builder(mContext);
        builder.setShowMessage(false);
        builder.setCancelable(true);
        LoadingDailog loadingDailog = builder.create();
        mLoadingDailog=new WeakReference<>(loadingDailog);
        loadingDailog.show();
        loadingDailog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if(disposable!=null&&disposable.get()!=null&&!disposable.get().isDisposed()){
                    disposable.get().dispose();
                }
            }
        });
        Window window = loadingDailog.getWindow();
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.dimAmount=0.35f;
        window.setAttributes(attributes);

    }

    /**
     * 通过klgCommonBeanList直接显示弹窗
     * @param mContext
     * @param fragmentManager
     * @param klgCommonBeanList
     * @param klgUrl
     * @param bean
     * @param listener
     */
    public static void opanKlgCardByList(Context mContext,FragmentManager fragmentManager,List<KlgCommonBean> klgCommonBeanList,String klgUrl,
                                         KlgCardDialogConfigBean bean,KlgCardDismissListener listener){
        if(KlgCourseWareManager.getVipLimitState(mContext)){
            KlgCourseWareManager.showTrainAgainDialog();
            return;
        }
        if(mLoadingDailog!=null&&mLoadingDailog.get()!=null&&
                mLoadingDailog.get().isShowing()){
            mLoadingDailog.get().dismiss();
        }
        if(klgCommonBeanList!=null&&klgCommonBeanList.size()>0){
            bean.setKlgCommonBeanList(klgCommonBeanList);
        }
        KlgCardDialogFragment.launchKlgCardDialogFragment(fragmentManager,bean,listener);

    }

    public static void opanKlgCardByList(Context mContext,FragmentManager fragmentManager,KlgCommonBean klgCommonBean,String klgUrl,
                                         KlgCardDialogConfigBean bean,KlgCardDismissListener listener){
        List<KlgCommonBean> beanList=new ArrayList<>();
        beanList.add(klgCommonBean);
        opanKlgCardByList(mContext,fragmentManager,beanList,klgUrl,bean,listener);
    }



    private static void getVersionControl(final Context mContext,final FragmentManager fragmentManager,final String klgCode,
                                          final KlgCardDialogConfigBean bean, final KlgCardDismissListener listener){
        if(disposable!=null&&disposable.get()!=null&&!disposable.get().isDisposed()){
            disposable.get().dispose();
        }
        Disposable disposable1=Network.getJsonData(KlgEnglishApi.class, KlgDbConstant.klg_baseUrl).getKlgVersion()
                .compose(NetworkTransformer.<String>commonSchedulers()).
                subscribeWith(new NormalSubscriber<String>(){
                    @Override
                    public void onNext(String stringKlgApiResponse) {
                        super.onNext(stringKlgApiResponse);
                        Log.e("aaaaaaaa","onNext:"+stringKlgApiResponse);
                        if(TextUtils.equals("v5.4",stringKlgApiResponse)){
                            getKnowledgeConfigMsg(mContext,fragmentManager,klgCode,bean,listener);
                        }else{
                            getV56VersionConfigMsg(mContext,fragmentManager,klgCode,bean,listener);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Log.e("aaaaaaaa","onError:"+e.toString());
                        getKnowledgeConfigMsg(mContext,fragmentManager,klgCode,bean,listener);
//                        iEnglishCardStudyView.loadingFailure(ErrorStates.NETERROR);
                    }
                });
        disposable=new WeakReference<>(disposable1);
    }

    private static void getKnowledgeConfigMsg(final Context mContext,final FragmentManager fragmentManager,final String klgCode,
                                       final KlgCardDialogConfigBean bean,final KlgCardDismissListener listener){
        Disposable disposable1= Network.getJsonData(KlgEnglishApi.class, KlgDbConstant.klg_baseUrl).getPlatFormConfigure()
                .compose(NetworkTransformer.<KlgApiResponse<ResourcePlatFormConfigure>>commonSchedulers()).
                subscribeWith(new NormalSubscriber<KlgApiResponse<ResourcePlatFormConfigure>>(){
                    @Override
                    public void onNext(KlgApiResponse<ResourcePlatFormConfigure> stringKlgApiResponse) {
                        super.onNext(stringKlgApiResponse);
                        if(stringKlgApiResponse.getState()==1){
                            if(TextUtils.isEmpty( KlgDbConstant.mediaUrl)){
                                KlgDbConstant.mediaUrl="http://"+stringKlgApiResponse.getData().getHttpIP()+":"+stringKlgApiResponse.getData().getHttpPort()+"/";
                            }
                            if(TextUtils.isEmpty(klgCode)){
                                showNoKlgDetailsDialog(fragmentManager);
                            }else {
                                String[] split = klgCode.split("\\|");
                                if(split.length<2){
                                    getKnowledgeNewCardMsg(mContext,fragmentManager,klgCode,bean,listener);
                                }else{
                                    if(klgCommonBeanList==null){
                                        klgCommonBeanList = new ArrayList<>();
                                    }else{
                                        klgCommonBeanList.clear();
                                    }
                                    currentKlgIndex=0;
                                    for (int i = 0; i <split.length ; i++) {
                                        getMoreKnowledgeNewCardMsg(mContext,fragmentManager,split[i],bean,
                                                listener,split.length);
                                    }
                                }
                            }
                        }else{
                            showNoKlgDetailsDialog(fragmentManager);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        showNoKlgDetailsDialog(fragmentManager);
                    }
                });
        disposable=new WeakReference<>(disposable1);
    }


    private static void getV56VersionConfigMsg(final Context mContext,final FragmentManager fragmentManager,final String klgCode,
                                               final KlgCardDialogConfigBean bean,final KlgCardDismissListener listener){
        Disposable disposable1 = Network.getJsonData(KlgEnglishApi.class, KlgDbConstant.klg_baseUrl).getObsConfig().compose(NetworkTransformer.<ObsConfigMsgBean>commonSchedulers()).
                subscribeWith(new NormalSubscriber<ObsConfigMsgBean>(){
                    @Override
                    public void onNext(@NotNull ObsConfigMsgBean stringKlgApiResponse) {
                        super.onNext(stringKlgApiResponse);
                        if(stringKlgApiResponse!=null){
                            KlgDbConstant.mediaUrl="http://"+stringKlgApiResponse.getBucketName()+"."+stringKlgApiResponse.getEndpoint()+"/";
                        }else{
                            getKnowledgeConfigMsg(mContext,fragmentManager,klgCode,bean,listener);
                            return;
                        }
                        if(TextUtils.isEmpty(klgCode)){
                            showNoKlgDetailsDialog(fragmentManager);
                        }else {
                            String[] split = klgCode.split("\\|");
                            if(split.length<2){
                                getKnowledgeNewCardMsg(mContext,fragmentManager,klgCode,bean,listener);
                            }else{
                                if(klgCommonBeanList==null){
                                    klgCommonBeanList = new ArrayList<>();
                                }else{
                                    klgCommonBeanList.clear();
                                }
                                currentKlgIndex=0;
                                for (int i = 0; i <split.length ; i++) {
                                    getMoreKnowledgeNewCardMsg(mContext,fragmentManager,split[i],bean,listener,split.length);
                                }
                            }
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        getKnowledgeConfigMsg(mContext,fragmentManager,klgCode,bean,listener);
//                        showNoKlgDetailsDialog(mContext);
                    }
                });
        disposable=new WeakReference<>(disposable1);
    }


    private static void getKnowledgeNewCardMsg(final Context mContext,final FragmentManager fragmentManager,final String klgCode,
                                        final KlgCardDialogConfigBean bean,final KlgCardDismissListener listener){
        Disposable disposable1=Network.getJsonData(KlgEnglishApi.class,KlgDbConstant.klg_baseUrl)
                .getEnglishCardByCode(klgCode).compose(NetworkTransformer.<KlgApiResponse<EnglishCardSource>>commonSchedulers()).
                subscribeWith(new NormalSubscriber<KlgApiResponse<EnglishCardSource>>(){
                    @Override
                    public void onNext(KlgApiResponse<EnglishCardSource> englishCardSourceKlgApiResponse) {
                        super.onNext(englishCardSourceKlgApiResponse);
                        if(englishCardSourceKlgApiResponse.getState()==1){
                            KlgCommonBean commonBean = buidKlgCommonEntity(mContext, englishCardSourceKlgApiResponse.getData());
                            List<KlgCommonBean> list=new ArrayList<>();
                            if(commonBean!=null){
                                list.add(commonBean);
                            }
                            opanKlgCardByList(mContext,fragmentManager,list,"",bean,listener);
                        }else{
                            getKnowledgeCardMsg(mContext,fragmentManager,klgCode,bean,listener);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        getKnowledgeCardMsg(mContext,fragmentManager,klgCode,bean,listener);
                    }
                });
        disposable=new WeakReference<>(disposable1);
    }


    private static void getMoreKnowledgeNewCardMsg(final Context mContext, final FragmentManager fragmentManager, final String klgCode,
                                                   final KlgCardDialogConfigBean bean, final KlgCardDismissListener listener, final int totalCount){

        if(!TextUtils.isEmpty(klgCode)&&klgCode.length()>2&&
                TextUtils.equals("G",klgCode.substring(klgCode.length()-2,klgCode.length()-1))){//esp获取知识点处理
            Disposable disposable1= Network.getJsonData(KlgEnglishApi.class,KlgDbConstant.klg_baseUrl).
                    getESPMaterialCardByCode(klgCode)
                    .compose(NetworkTransformer.<KlgApiResponse<ESPCardSource>>commonSchedulers())
                    .subscribeWith(new NormalSubscriber<KlgApiResponse<ESPCardSource>>(){
                        @Override
                        public void onNext(@NotNull KlgApiResponse<ESPCardSource> englishCardSourceKlgApiResponse) {
                            super.onNext(englishCardSourceKlgApiResponse);
                            currentKlgIndex++;
                            if(englishCardSourceKlgApiResponse.getState()==1&&englishCardSourceKlgApiResponse.getData()!=null){
                                KlgCommonBean commonBean = buildCommonBean(englishCardSourceKlgApiResponse.getData());
                                if(commonBean!=null){
                                    klgCommonBeanList.add(commonBean);
                                }

                            }
                            if(currentKlgIndex==totalCount){
                                showMoreKnowledgeCardDialog(fragmentManager,klgCommonBeanList,bean,listener);
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                            currentKlgIndex++;
                            if(currentKlgIndex==totalCount){
                                showMoreKnowledgeCardDialog(fragmentManager,klgCommonBeanList,bean,listener);
                            }
                        }
                    });
            disposable=new WeakReference<>(disposable1);

        }else{//非Esp获取知识点处理
            Disposable disposable1=Network.getJsonData(KlgEnglishApi.class,KlgDbConstant.klg_baseUrl)
                    .getEnglishCardByCode(klgCode).compose(NetworkTransformer.<KlgApiResponse<EnglishCardSource>>commonSchedulers()).
                            subscribeWith(new NormalSubscriber<KlgApiResponse<EnglishCardSource>>(){
                                @Override
                                public void onNext(@NotNull KlgApiResponse<EnglishCardSource> englishCardSourceKlgApiResponse) {
                                    super.onNext(englishCardSourceKlgApiResponse);
                                    currentKlgIndex++;
                                    if(englishCardSourceKlgApiResponse.getState()==1&&englishCardSourceKlgApiResponse.getData()!=null){
                                        KlgCommonBean commonBean = buidKlgCommonEntity(mContext, englishCardSourceKlgApiResponse.getData());
                                        if(commonBean!=null){
                                            klgCommonBeanList.add(commonBean);
                                        }

                                    }
                                    if(currentKlgIndex==totalCount){
                                        showMoreKnowledgeCardDialog(fragmentManager,klgCommonBeanList,bean,listener);
                                    }
                                }

                                @Override
                                public void onError(Throwable e) {
                                    super.onError(e);
                                    currentKlgIndex++;
                                    if(currentKlgIndex==totalCount){
                                        showMoreKnowledgeCardDialog(fragmentManager,klgCommonBeanList,bean,listener);
                                    }
                                }
                            });
            disposable=new WeakReference<>(disposable1);
        }


    }




    private static void getKnowledgeCardMsg(final Context mContext, final FragmentManager fragmentManager, final String klgCode,
                                            final KlgCardDialogConfigBean bean, final KlgCardDismissListener listener){
        Disposable disposable1=Network.getJsonData(KlgEnglishApi.class,KlgDbConstant.klg_baseUrl).getEnglishOldCardByCode(klgCode).compose(NetworkTransformer.<KlgApiResponse<EnglishCardSource>>commonSchedulers()).
                subscribeWith(new NormalSubscriber<KlgApiResponse<EnglishCardSource>>(){
                    @Override
                    public void onNext(KlgApiResponse<EnglishCardSource> englishCardSourceKlgApiResponse) {
                        super.onNext(englishCardSourceKlgApiResponse);
                        if(englishCardSourceKlgApiResponse.getState()==1){
                            KlgCommonBean commonBean = buidKlgCommonEntity(mContext, englishCardSourceKlgApiResponse.getData());
                            List<KlgCommonBean> list=new ArrayList<>();
                            if(commonBean!=null){
                                list.add(commonBean);
                            }
                            opanKlgCardByList(mContext,fragmentManager,list,"",bean,listener);
                        }else{
                            showNoKlgDetailsDialog(fragmentManager);
                        }
                        if(mLoadingDailog!=null&&mLoadingDailog.get()!=null&&mLoadingDailog.get().isShowing()){
                            mLoadingDailog.get().dismiss();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        showNoKlgDetailsDialog(fragmentManager);
                    }
                });
        disposable=new WeakReference<>(disposable1);
    }

    public static void getDigitalizeCode(final Context mContext,final FragmentManager fragmentManager,final String klgCode,
                                         final KlgCardDialogConfigBean bean, final KlgCardDismissListener listener){
        Network.getJsonData(KlgEnglishApi.class,KlgDbConstant.klgPublicUrl).
                getDigitalizeCode(new DigitalizeCodeBean(klgCode,""))
                .compose(NetworkTransformer.<DigitalizeCodeResponce>commonSchedulers())
                .subscribe(new NormalSubscriber<DigitalizeCodeResponce>(){
                    @Override
                    public void onNext(@NotNull DigitalizeCodeResponce responce) {
                        super.onNext(responce);
                        if(responce.getStatus()==1&&!TextUtils.isEmpty(responce.getData())){
                            getVersionControl(mContext,fragmentManager,responce.getData(),bean,listener);
                        }else{
                            getVersionControl(mContext,fragmentManager,klgCode,bean,listener);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        getVersionControl(mContext,fragmentManager,klgCode,bean,listener);
                    }
                });
    }



    /**
     * 构造知识点课件数据公共模型 非ESP知识点类型
     * @param cardSource
     * @return
     */
    private static KlgCommonBean buidKlgCommonEntity(Context mContext,EnglishCardSource cardSource){
        if(cardSource==null){
            return null;
        }
        KlgCommonBean klgCommonBean=new KlgCommonBean();
        klgCommonBean.setKlgCode(cardSource.getKlgCode());
        klgCommonBean.setKlgName(cardSource.getKlgName());
        klgCommonBean.setKlgType(cardSource.getKlgType());
        if(cardSource.getWordData()!=null){
            klgCommonBean.setUn_phonetic(UniCodeUtils.convertToChinese(cardSource.getWordData().getUN_phonetic()));
            if(!TextUtils.isEmpty(cardSource.getWordData().getUN_voice())){
                klgCommonBean.setUn_voice( KlgDbConstant.mediaUrl+cardSource.getWordData().getUN_voice());
            }
            klgCommonBean.setUs_phonetic(UniCodeUtils.convertToChinese(cardSource.getWordData().getUS_phonetic()));
            if(!TextUtils.isEmpty(cardSource.getWordData().getUS_voice())){
                klgCommonBean.setUs_voice(KlgDbConstant.mediaUrl+cardSource.getWordData().getUS_voice());
            }
            if(TextUtils.equals("ESP",cardSource.getKlgType())){
                String picture=cardSource.getWordData().getClassicSen();
                if(!TextUtils.isEmpty(picture)&&picture.indexOf(".")!=-1){
                    String format = (picture.substring(picture.lastIndexOf(".") + 1)+"").toLowerCase();
                    if(TextUtils.equals(format,"bmp")||
                            TextUtils.equals(format,"jpg")||
                            TextUtils.equals(format,"gif")||
                            TextUtils.equals(format,"png")||
                            TextUtils.equals(format,"jpeg")){
                        klgCommonBean.setClassicSen(cardSource.getWordData().getClassicSen());
                    }
                }
                if(cardSource.getWordData().getExplainList()!=null&&cardSource.getWordData().getExplainList().size()>5){
                    klgCommonBean.setShowMoreMeaning(true);
                    klgCommonBean.setShortExplan(buildExplainString(cardSource.getWordData().getExplainList(),false));
                }else{
                    klgCommonBean.setShowMoreMeaning(false);
                }
            }else{
                klgCommonBean.setClassicSen(buildNewClassicSenString(cardSource.getWordData().getClassicSen()));
            }
            klgCommonBean.setClassicTrain(cardSource.getWordData().getClassicTran());
            if(!TextUtils.isEmpty(cardSource.getWordData().getClassicVoice())){
                klgCommonBean.setClassicVoice(KlgDbConstant.mediaUrl+cardSource.getWordData().getClassicVoice());
            }
            klgCommonBean.setExplain(buildExplainString(cardSource.getWordData().getExplainList(),true));
        }
        if(cardSource.getExpressionData()!=null&&cardSource.getExpressionData().getUsageList()!=null&&cardSource.getExpressionData().getUsageList().size()>0){
//            klgCommonBean.setExplain(cardSource.getExpressionData().getUsageList().get(0).getExplain().trim());
//            klgCommonBean.setUsage(cardSource.getExpressionData().getUsageList().get(0).getUsage());
            if(cardSource.getExpressionData().getUsageList()!=null&&cardSource.getExpressionData().getUsageList().size()>0){
                StringBuilder stringBuilder=new StringBuilder();
                for (ExpressionAndUsageModel expressionAndUsageModel:cardSource.getExpressionData().getUsageList()){
                    stringBuilder.append(expressionAndUsageModel.getUsage());
                    stringBuilder.append("\n");
                }
                klgCommonBean.setUsage(stringBuilder.toString());
            }
            if(cardSource.getExpressionData().getUsageList()!=null&&cardSource.getExpressionData().getUsageList().size()>0){
                StringBuilder stringBuilder=new StringBuilder();
                for (ExpressionAndUsageModel expressionAndUsageModel:cardSource.getExpressionData().getUsageList()){
                    stringBuilder.append(expressionAndUsageModel.getExplain().trim());
                    stringBuilder.append("\n");
                }
                klgCommonBean.setExplain(stringBuilder.toString());
            }
        }
        if(cardSource.getSyntaxData()!=null){
            if(!TextUtils.isEmpty(cardSource.getSyntaxData().getClassicSen())){
                klgCommonBean.setClassicSen(buildNewClassicSenString(cardSource.getSyntaxData().getClassicSen()));
            }

            klgCommonBean.setClassicTrain(cardSource.getSyntaxData().getClassicTran());
            klgCommonBean.setParaphrase(cardSource.getSyntaxData().getThemeName());
            if(!TextUtils.isEmpty(cardSource.getSyntaxData().getClassicVoice())){
                klgCommonBean.setClassicVoice(KlgDbConstant.mediaUrl+cardSource.getSyntaxData().getClassicVoice());
            }
            if(cardSource.getSyntaxData().getUsageList()!=null&&cardSource.getSyntaxData().getUsageList().size()>0){
//                klgCommonBean.setUsage(cardSource.getSyntaxData().getUsageList().get(0).getUsage());
                StringBuilder stringBuilder=new StringBuilder();
                for (ExpressionAndUsageModel expressionAndUsageModel:cardSource.getSyntaxData().getUsageList()){
                    stringBuilder.append(expressionAndUsageModel.getUsage());
                    stringBuilder.append("\n");
                }
                klgCommonBean.setUsage(stringBuilder.toString());
            }
        }

        return klgCommonBean;
    }

    /**
     * 构造释义内容
     * @param explainModelList 释义list
     * @return 释义内容
     */
    private static String buildExplainString(List<WordExplainModel> explainModelList,boolean max){
        StringBuilder explainString=new StringBuilder();
        int index=0;
        if(explainModelList!=null){
            for (WordExplainModel wordExplainModel:explainModelList){
                explainString.append(""+wordExplainModel.getCxAndExplain());
                if(index!=explainModelList.size()-1){
                    explainString.append("<br>");
                }
                index++;
                if(!max&&index==5){
                    break;
                }
            }
//            return Html.fromHtml(explainString.toString().replace("<&2&>","$&2&$")).toString().trim().replace("$&2&$","<&2&>");
            return explainString.toString().replace("\n","|").replace("<br>","|").replace("<","&gt;")
                    .replace(">","&gl;").replace("|","<br>");
//            return Html.fromHtml(explainString.toString().replace("<&2&>","$&2&$")).toString().trim().replace("$&2&$","<&2&>");
        }else {
            return "";
        }
    }

    private static String buildNewClassicSenString(String classicSen){
        if (TextUtils.isEmpty(classicSen)) {
            return classicSen;
        }
        String newString=classicSen.replaceAll("</STRONG>","</font>")
                .replaceAll("<STRONG>","<font color='#0077f0'>")
                .replaceAll("</strong>","</font>")
                .replaceAll("<strong>","<font color='#0077f0'>");
        return newString.trim();
    }


    /**
     * 构造知识点课件公共模型 ESP类型
     * @param espCardSource 原数据模型
     * @return 新的通用模型
     */
    private static KlgCommonBean buildCommonBean(ESPCardSource espCardSource){

        KlgCommonBean klgCommonBean=new KlgCommonBean();
        klgCommonBean.setKlgCode(espCardSource.getKlgCode());
        klgCommonBean.setKlgName(espCardSource.getKlgName());
        klgCommonBean.setKlgType("ESP");
        if(!TextUtils.isEmpty(espCardSource.getUN_voice())){
            klgCommonBean.setUn_voice(KlgDbConstant.mediaUrl+espCardSource.getUN_voice());
        }
        klgCommonBean.setUn_phonetic(UniCodeUtils.convertToChinese(espCardSource.getUN_phonetic()));
        if(!TextUtils.isEmpty(espCardSource.getUS_voice())){
            klgCommonBean.setUs_voice(KlgDbConstant.mediaUrl+espCardSource.getUS_voice());
        }
        klgCommonBean.setUs_phonetic(UniCodeUtils.convertToChinese(espCardSource.getUS_phonetic()));
        klgCommonBean.setClassicSen(espCardSource.getPicturePath());
        klgCommonBean.setExplain(buildESPExplainString(espCardSource.getMeaningList(),true));
        klgCommonBean.setMeaningTime(espCardSource.getMeaningTime());
        klgCommonBean.setEnglishMeaning(espCardSource.getEnglishMeaning());
        klgCommonBean.setMeaningVoice(espCardSource.getMeaningVoice());
        if(espCardSource.getMeaningList()!=null&&espCardSource.getMeaningList().size()>5){
            klgCommonBean.setShowMoreMeaning(true);
            klgCommonBean.setShortExplan(buildESPExplainString(espCardSource.getMeaningList(),false));
        }else{
            klgCommonBean.setShowMoreMeaning(false);
        }
        return klgCommonBean;
    }


    /**
     * 构造释义内容
     * @param explainModelList
     * @return
     */
    private static String buildESPExplainString(List<ChineseMeaning> explainModelList, boolean max){
        StringBuffer explainString=new StringBuffer();
        int index=0;
        if(explainModelList!=null){
            for (ChineseMeaning wordExplainModel:explainModelList){
                explainString.append(""+wordExplainModel.getChineseMeaning());
                if(index!=explainModelList.size()-1){
                    explainString.append("<br/>");
                }
                index++;
                if(!max&&index==5){
                    break;
                }
            }
            return Html.fromHtml(explainString.toString()).toString().trim();
        }else {
            return "";
        }
    }



    /**
     * 同时展示多个知识点弹窗 非电子教材库用
     * @param fragmentManager fragment管理器
     * @param klgCommonBeanList 知识点list
     */
    public static void showMoreKnowledgeCardDialog(FragmentManager fragmentManager, List<KlgCommonBean> klgCommonBeanList,
                                                   KlgCardDialogConfigBean bean,KlgCardDismissListener listener){
        if(mLoadingDailog!=null&&mLoadingDailog.get()!=null&&
                mLoadingDailog.get().isShowing()){
            mLoadingDailog.get().dismiss();
        }
        bean.setKlgCommonBeanList(klgCommonBeanList);
        KlgCardDialogFragment.launchKlgCardDialogFragment(fragmentManager,bean,listener);


    }

    /**
     * 来源于课前预习的对接定制
     * @param mContext 上下文
     * @param klgCommonBeanList 知识点list
     */
    public static void showMoreKnowledgeCardDialog(Context mContext,FragmentManager fragmentManager,
                                                   List<KlgCommonBean> klgCommonBeanList, boolean isRetractCard,
                                                   boolean hasCustomBtn,int fromType,int userType ,
                                                   final KlgCardDismissListener listener){
        Log.e("eee",isRetractCard+""+hasCustomBtn);
        if(klgCommonBeanList!=null&&fromType==0){
            for (KlgCommonBean klgCommonBean:klgCommonBeanList){
                if(!TextUtils.isEmpty(klgCommonBean.getUn_voice())){
                    klgCommonBean.setUn_voice(KlgCourseWareManager.getMediaUrl(mContext)+""+klgCommonBean.getUn_voice());
                }
                if(!TextUtils.isEmpty(klgCommonBean.getUs_voice())){
                    klgCommonBean.setUs_voice(KlgCourseWareManager.getMediaUrl(mContext)+""+klgCommonBean.getUs_voice());
                }
                if(TextUtils.isEmpty(klgCommonBean.getExplain())||TextUtils.isEmpty(klgCommonBean.getExplain().trim())){
                    klgCommonBean.setExplain(mContext.getString(R.string.klg_no_meaning));
                    klgCommonBean.setHideBtn(true);
                }else{
                    klgCommonBean.setExplain(klgCommonBean.getExplain().replace("\n","<br>"));
                }
            }
        }
        KlgCardDialogConfigBean bean=new KlgCardDialogConfigBean(userType);
        bean.setHasNote(hasCustomBtn);
        bean.setHasSave(true);
//        bean.setHasCustomBtn(hasCustomBtn);
//        bean.setCustomBtnName("做笔记");
        showMoreKnowledgeCardDialog(fragmentManager,klgCommonBeanList,bean,listener);
    }

    public interface KlgCardDismissListener{
        void onCardDismiss(int dismissType, int position, KlgCommonBean klgCommonBean, String  tag);
    }

    public interface KlgCollectionWordCallBack{
        void updateCollectionState(int state);
    }



    /**
     * 查询知识点失败弹窗
     */
    public static void showNoKlgDetailsDialog(FragmentManager fragmentManager){
        KlgCardDialogFragment.launchKlgCardDialogFragment(fragmentManager,null);

    }




    /**
     * 专业化过关训练-阅读训练专用
     * @param mContext 上下文
     * @param klgCode 知识点id
     * @param url 知识点url
     * @param haiCustomBtn 更多功能开放
     * @param customBtnName 功能名称
     */
    public static void openKlgDialog(Context mContext,FragmentManager fragmentManager,String klgCode,String url,boolean haiCustomBtn,
                              String customBtnName,KlgCardDismissListener listener,
                              String passTrainUrl,String trainSystem,String userID){
        if(!TextUtils.isEmpty(url)){
            KlgDbConstant.klg_baseUrl=url;
        }
        KlgDbConstant.mediaUrl="";
        mLoadingDailog=null;
        getKlghaiInBook(fragmentManager,klgCode,passTrainUrl,trainSystem,userID,mContext,url,customBtnName,listener);
    }

    private static void getKlghaiInBook(final FragmentManager fragmentManager,final String klgCode,String passTrainUrl,String trainSystem,String userID,
                                 final Context mContext,final String url,final String customBtnName,final KlgCardDismissListener listener){
        if(!(mLoadingDailog!=null&&mLoadingDailog.get()!=null&&mLoadingDailog.get().isShowing())){
            LoadingDailog.Builder builder = new LoadingDailog.Builder(mContext);
            builder.setShowMessage(false);
            builder.setCancelable(true);
            LoadingDailog loadingDailog1 = builder.create();
            mLoadingDailog=new WeakReference<>(loadingDailog1);
            loadingDailog1.show();
            loadingDailog1.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if(disposable!=null&&disposable.get()!=null&&!disposable.get().isDisposed()){
                        disposable.get().dispose();
                    }
                }
            });
            Window window = mLoadingDailog.get().getWindow();
            if(window==null){
                return;
            }
            WindowManager.LayoutParams attributes = window.getAttributes();
            attributes.dimAmount=0.35f;
            window.setAttributes(attributes);
        }else {
            mLoadingDailog.get().show();
        }
        if(disposable!=null&&disposable.get()!=null&&!disposable.get().isDisposed()){
            disposable.get().dispose();
        }
        WordBookRequestBean bean=new WordBookRequestBean(klgCode,trainSystem,"123",userID);
        Disposable disposable1 = Network.getJsonData(PassTrainApi.class,passTrainUrl)
                .isInWorkBook(bean)
                .compose(NetworkTransformer.<PassTrainResponce>commonSchedulers())
                .subscribeWith(new NormalSubscriber<PassTrainResponce>(){

                    @Override
                    public void onNext(PassTrainResponce passTrainResponce) {
                        super.onNext(passTrainResponce);
                        boolean hasCustomTrain=true;
                        if(passTrainResponce.getStatus()>=0){
                            hasCustomTrain=passTrainResponce.getData().getIsInWordBook()!=1;
                        }else{
                            mLoadingDailog.get().dismiss();
                            showNoKlgDetailsDialog(fragmentManager);
                            return;
                        }
                        KlgCardDialogConfigBean bean=new KlgCardDialogConfigBean(2);
                        bean.setSystemID("627");
                        bean.setHasCustomBtn(hasCustomTrain);
                        bean.setCustomBtnName(customBtnName);
                        openKlgCardByID(mContext,fragmentManager,klgCode,url,bean,listener);
                        Log.e("aaaa","onNext");
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Log.e("aaaa","onError");
                        mLoadingDailog.get().dismiss();
                        showNoKlgDetailsDialog(fragmentManager);
                    }

                });
        disposable=new WeakReference<>(disposable1);
    }
}
